package ee.rsi2m.goproject.view;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.TextView;
import ee.rsi2m.goproject.MenuActivity;
import ee.rsi2m.goproject.R;
import ee.rsi2m.goproject.model.GoBoard;
import ee.rsi2m.goproject.service.SurfaceViewThread;
import ee.rsi2m.goproject.util.BoardLoader;

public class GoBoardView extends SurfaceView implements SurfaceHolder.Callback {

	private SurfaceViewThread thread;
	private int x, y;
	private int stoneX, stoneY = 0;
	private Context context;
	private SurfaceHolder holder;
	private int size;
	public static GoBoard board;
	private Bitmap background;
	private Bitmap scaled;
	public boolean opponentPassed, playerPassed = false;
	ImageButton imageButton;

	Paint paint = new Paint();

	public GoBoardView(Context context, int width, int height, int size, int handicap) {

		super(context);
		this.context = context;
		this.size = size;
		holder = getHolder();
		holder.addCallback(this);
		holder = getHolder();
		holder.addCallback(this);
		// String k = a.getString(R.styleable.GoBoardView_hui);
		// Log.w("size",""+k);

		board = new GoBoard(19, 800, 480);
		// MenuActivity.playGTP("boardsize "+board.size);
		// MenuActivity.playGTP("level 1");
		thread = new SurfaceViewThread(holder, board, context, this, 0);

		// setFocusable(true);

	}

	public GoBoardView(Context context, AttributeSet attrs) {

		super(context, attrs);

		this.context = context;
		holder = getHolder();
		holder.addCallback(this);
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GoBoardView);
		// String k = a.getString(R.styleable.GoBoardView_hui);
		// Log.w("size",""+k);
		Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

		SharedPreferences myPrefs = context.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);

		board = new GoBoard(myPrefs.getInt("boardSize", 9), display.getWidth(), display.getHeight());

		// MenuActivity.playGTP("boardsize "+board.size);
		// MenuActivity.playGTP("level 1");
		thread = new SurfaceViewThread(holder, board, context, this, 0);

	}

	@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
	}

	/*
	 * returns position of the point relativelly to the center line of screen's
	 * width
	 */

	@Override
	public boolean getGlobalVisibleRect(Rect r, android.graphics.Point globalOffset) {
		// TODO Auto-generated method stub
		return super.getGlobalVisibleRect(r, globalOffset);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

		/*
		 * boolean retry = true; thread.setRunning(false); while (retry) { try {
		 * thread.join(); retry = false; } catch (InterruptedException e) {
		 * 
		 * } } board = new GoBoard(size, height, width); thread = new
		 * SurfaceViewThread(holder, board, context); thread.setRunning(true);
		 * thread.start();
		 */

	}

	public boolean undo() {
		// showOpponentPassedNotification();
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// showOpponentPassedNotification();
		thread.doTouch(event, imageButton);

		Log.w("button", (imageButton == null) + "");
		// invalidate();
		return true;
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		thread.setRunning(false);

		while (thread != null) {
			try {
				thread.join();
				thread = null;
			} catch (InterruptedException e) {
			}
		}

	}

	private void showOpponentPassedNotification() {
		Animation a = AnimationUtils.loadAnimation(context, R.anim.animation);
		a.reset();
		TextView tv = (TextView) ((Activity) context).findViewById(R.id.thirdTextView);
		tv.setVisibility(View.VISIBLE);
		tv.startAnimation(a);
		tv.setVisibility(View.INVISIBLE);
	}

	/*
	 * public void onDraw(Canvas canvas) { canvas.drawBitmap(scaled, 0, 0,
	 * n//goBoardView.undo(); ull); // draw the background }
	 */

	public void surfaceCreated(SurfaceHolder holder) {
		// start the thread here so that we don't busy-wait in run()
		// waiting for the surface to be created
		/*
		 * background = BitmapFactory.decodeResource(getResources(),
		 * R.drawable.gamescreenbackground); float scale =
		 * background.getHeight()/getHeight(); int newWidth =
		 * Math.round(background.getWidth()/scale); int newHeight =
		 * Math.round(background.getHeight()/scale); scaled =
		 * Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
		 */
		if (imageButton == null) {
			imageButton = (ImageButton) ((Activity) context).findViewById(R.id.finishMove);
			imageButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					imageButton.setSelected(false);
					imageButton.setEnabled(false);
					if (thread.isGameBegan()) {
						thread.putStone();
						opponentPassed = !thread.makeMoveByBot();
						if (opponentPassed) {
							showOpponentPassedNotification();
						}
						Log.w("GAMESTATE",MenuActivity.playGTP("showboard"));
						Log.w("menu Save:", MenuActivity.playGTP("printsgf /data/data/ee.rsi2m.goproject/autoSave"));
					}
				}
			});
		}
		if (thread == null) {
			thread = new SurfaceViewThread(holder, board, context, this, 0);
			
			Log.w("restart",MenuActivity.playGTP("loadsgf"));
			Log.w("restart",MenuActivity.playGTP("showboard"));
			BoardLoader.loadBoad(thread,board,MenuActivity.playGTP("showboard"));
		}
		thread.setRunning(true);
		thread.start();

		// ImageButton imageButton = (ImageButton)
		// findViewById(R.id.finishMove);

	}

	private void showScoreAnimation(String score) {
		Animation a = AnimationUtils.loadAnimation(context, R.anim.animation);
		a.reset();
		TextView tv = (TextView) ((Activity) context).findViewById(R.id.thirdTextView);
		tv.setText(score);
		tv.setVisibility(View.VISIBLE);
		tv.startAnimation(a);
		tv.setVisibility(View.INVISIBLE);
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		// Handle item selection
		switch (item.getItemId()) {
		case R.id.undo:
			//Log.w("menu", MenuActivity.playGTP("printsgf /data/data/ee.rsi2m.goproject/files/autoSave"));
			thread.pass();
			playerPassed = true;
			if (playerPassed && opponentPassed) {
				Log.w("pass", "both!");
				showScoreAnimation(thread.getScore());
			}

			return true;
		}
		return true;
	}

	public void reloadGame() {
		Log.w("menu", MenuActivity.playGTP("loadsgf /data/data/ee.rsi2m.goproject/autoSave"));

	}

}